package com.sprucetec.livechat.util;

import com.alibaba.fastjson.JSONObject;
import com.sprucetec.livechat.model.vo.ResponseJson;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName WebSocketUtil
 * @Description:
 * @Author Kenny
 * @Date 2020/4/3
 **/
public class WebSocketUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketUtil.class);

    public static JSONObject getParameters(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 客服端发送过来的消息
        String request = ((TextWebSocketFrame) frame).text();
        LOGGER.info("服务端收到新信息：" + request);
        JSONObject param = null;
        try {
            param = JSONObject.parseObject(request);
        } catch (Exception e) {
            sendErrorMessage(ctx, "JSON字符串转换出错！");
            e.printStackTrace();
        }
        if (param == null) {
            sendErrorMessage(ctx, "参数为空！");
            return null;
        }

        String type = (String) param.get("type");
        return param;
    }


    public static void sendErrorMessage(ChannelHandlerContext ctx, String errorMsg) {
        String responseJson = new ResponseJson()
                .error(errorMsg)
                .toString();
        ctx.channel().writeAndFlush(new TextWebSocketFrame(responseJson));
    }

}
